<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据日期" prop="registerTime">
        <el-date-picker clearable
                        v-model="queryParams.registerTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择单据日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="问题描述" prop="questionDesc">
        <el-input
          v-model="queryParams.questionDesc"
          placeholder="请输入问题描述"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="故障分析" prop="faultAnalysis">
        <el-input
          v-model="queryParams.faultAnalysis"
          placeholder="请输入故障分析"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="处理日期" prop="handleTime">
        <el-date-picker clearable
                        v-model="queryParams.handleTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择处理日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="修补配件" prop="repairPart">
        <el-select v-model="queryParams.repairPart" placeholder="请选择修补配件" clearable>
          <el-option
            v-for="dict in dict.type.accessory_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="配件ID" prop="partId">
        <el-input
          v-model="queryParams.partId"
          placeholder="请输入配件ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="配件费用" prop="partCost">
        <el-input
          v-model="queryParams.partCost"
          placeholder="请输入配件费用"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登记信息来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择登记信息来源" clearable>
          <el-option
            v-for="dict in dict.type.sale_register_source"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['saleManagement:saleRegister:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['saleManagement:saleRegister:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['saleManagement:saleRegister:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['saleManagement:saleRegister:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="saleRegisterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="center" prop="registerId" />
      <el-table-column label="单据日期" align="center" prop="registerTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="问题描述" align="center" prop="questionDesc" />
      <el-table-column label="客诉图片" align="center" prop="picture" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.picture" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="故障分析" align="center" prop="faultAnalysis" />
      <el-table-column label="处理结果" align="center" prop="handleResult" />
      <el-table-column label="处理日期" align="center" prop="handleTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.handleTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修补配件" align="center" prop="repairPart">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.accessory_type" :value="scope.row.repairPart"/>
        </template>
      </el-table-column>
      <el-table-column label="配件ID" align="center" prop="partId" />
      <el-table-column label="配件费用" align="center" prop="partCost" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="登记信息来源" align="center" prop="source">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sale_register_source" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['saleManagement:saleRegister:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['saleManagement:saleRegister:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
     <!-- 弹窗输入车辆ID或配件ID -->
     <el-dialog title="登记选择" :visible.sync="dialogFormVisible" v-if="dialogFormVisible" width="800px">
      <el-form ref="accessoryForm" :model="accessoryForm" :rules="accessoryFormRules">
        <el-form-item label="车辆ID或配件ID" prop="keyWord">
          <el-input v-model="accessoryForm.keyWord" placeholder="请输入车辆ID或配件ID"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAccessoryForm">确 定</el-button>
        <el-button @click="cancelAccessoryForm">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改售后登记对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-descriptions title="订单列表信息" direction="vertical" :column="4" border>
        <el-descriptions-item label="车辆ID" :span="2">{{ orderDetail.bicycleId }}</el-descriptions-item>
        <el-descriptions-item label="控制器号" :span="2">{{ orderDetail.controllerId }}</el-descriptions-item>
        <template v-for="item in (orderDetail.fittingValues || [])">
          <el-descriptions-item :label="item.fittingName" :span="2">{{ item.fitting }}</el-descriptions-item>
        </template>
        <el-descriptions-item label="客户" :span="2">{{ orderDetail.clientName }}</el-descriptions-item>
        <el-descriptions-item label="客户订单号" :span="2">{{ orderDetail.clientOrderNumber }}</el-descriptions-item>
        <el-descriptions-item label="生产订单号" :span="2">{{ orderDetail.clientOrderNumber }}</el-descriptions-item>
        <el-descriptions-item label="产品编码" :span="2">{{ orderDetail.productId }}</el-descriptions-item>
        <el-descriptions-item label="产品名称" :span="2">{{ orderDetail.productName }}</el-descriptions-item>
        <el-descriptions-item label="客户型号" :span="2">{{ orderDetail.customerModel }}</el-descriptions-item>
        <el-descriptions-item label="出库日期" :span="2">{{ orderDetail.outboundDate }}</el-descriptions-item>
      </el-descriptions>
      <el-row style="padding: 20px 0;font-weight: 700">
        登记信息
      </el-row>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="单据日期" prop="registerTime">
          <el-date-picker clearable
                          v-model="form.registerTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择单据日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="问题描述" prop="questionDesc">
          <el-input v-model="form.questionDesc" placeholder="请输入问题描述" />
        </el-form-item>
        <el-form-item label="客诉图片" prop="picture">
          <image-upload v-model="form.picture"/>
        </el-form-item>
        <el-form-item label="故障分析" prop="faultAnalysis">
          <el-input v-model="form.faultAnalysis" placeholder="请输入故障分析" />
        </el-form-item>
        <el-form-item label="处理结果" prop="handleResult">
          <el-input v-model="form.handleResult" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="修补配件" prop="repairPart">
          <el-select v-model="form.repairPart" placeholder="请选择修补配件">
            <el-option
              v-for="dict in dict.type.accessory_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="配件ID" prop="partId">
          <el-input v-model="form.partId" placeholder="请输入配件ID" />
        </el-form-item>
        <el-form-item label="配件费用" prop="partCost">
          <el-input v-model="form.partCost" placeholder="请输入配件费用" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="登记信息来源" prop="source">
          <el-select v-model="form.source" disabled placeholder="请选择登记信息来源">
            <el-option
              v-for="dict in dict.type.sale_register_source"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getOrderDetail, isExist } from '@/api/client/register'
import { listSaleRegister, getSaleRegister, delSaleRegister, addSaleRegister, updateSaleRegister } from "@/api/saleManagement/saleRegister/saleRegister.js";

export default {
  name: "SaleRegister",
  dicts: ['accessory_type', 'sale_register_source'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 售后登记表格数据
      saleRegisterList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registerTime: null,
        questionDesc: null,
        picture: null,
        faultAnalysis: null,
        handleResult: null,
        handleTime: null,
        repairPart: null,
        partId: null,
        partCost: null,
        source: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        registerTime: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
        questionDesc: [
          { required: true, message: "问题描述不能为空", trigger: "blur" }
        ],
        picture: [
          { required: true, message: "客诉图片不能为空", trigger: "blur" }
        ],
        faultAnalysis: [
          { required: true, message: "故障分析不能为空", trigger: "blur" }
        ],
        handleResult: [
          { required: true, message: "处理结果不能为空", trigger: "blur" }
        ],
        repairPart: [
          { required: true, message: "修补配件不能为空", trigger: "change" }
        ],
        partId: [
          { required: true, message: "配件ID不能为空", trigger: "blur" }
        ],
        partCost: [
          { required: true, message: "配件费用不能为空", trigger: "blur" }
        ],
      },
      dialogFormVisible: false,
      accessoryForm: {},
      orderDetail: {},
      accessoryFormRules: {
        keyWord: [
          { required: true, message: "请输入关键词", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //获取商品信息和登记信息
    async getOrderDetail(keyWord) {
      let resp = await getOrderDetail(keyWord)
      this.orderDetail = resp.data.orderDetail
    },
    /** 查询售后登记列表 */
    getList() {
      this.loading = true;
      listSaleRegister(this.queryParams).then(response => {
        this.saleRegisterList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        registerId: null,
        registerTime: null,
        questionDesc: null,
        picture: null,
        faultAnalysis: null,
        handleResult: null,
        repairPart: null,
        partId: null,
        partCost: null,
        remark: null,
        source: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.registerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.accessoryForm = {
        keyWord: undefined
      }
      this.resetForm('accessoryForm')
      this.dialogFormVisible = true;
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const registerId = row.registerId || this.ids
      await this.getOrderDetail(row.partId)
      await getSaleRegister(registerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改售后登记";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.registerId != null) {
            updateSaleRegister(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSaleRegister(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const registerIds = row.registerId || this.ids;
      this.$modal.confirm('是否确认删除售后登记编号为"' + registerIds + '"的数据项？').then(function() {
        return delSaleRegister(registerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('saleManagement/saleRegister/export', {
        ...this.queryParams
      }, `saleRegister_${new Date().getTime()}.xlsx`)
    },
    async submitAccessoryForm() {
      await this.$refs["accessoryForm"].validate(async valid => {
        if (valid) {
          let resp = await isExist(this.accessoryForm.keyWord)
          if(resp.code === 200) {
            await this.getOrderDetail(this.accessoryForm.keyWord)
            this.reset();
            this.cancelAccessoryForm()
            this.form.source = '02'
            this.open = true;
            this.title = "添加售后登记";
          }
        }
      })
    },
    cancelAccessoryForm() {
      this.accessoryForm = {
        keyWord: undefined
      }
      this.resetForm('accessoryForm')
      this.dialogFormVisible = false;
    }
  }
};
</script>
